import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    // 如果父路由有默认子路由，父路由不能命名（name），否则警告
    // name: 'layout',
    component: () => import('@/views/layout/index.vue'),
    children: [
      {
        path: '', // path为空,会作为默认子路由渲染
        name: 'home',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: '/article',
        name: 'article',
        component: () => import('@/views/article/')
      },
      {
        path: '/publish',
        name: 'publish',
        component: () => import('@/views/publish/')
      },
      {
        path: '/image',
        name: 'image',
        component: () => import('@/views/images/')
      },
      {
        path: '/comment',
        name: 'comment',
        component: () => import('@/views/comment/')
      },
      {
        path: '/settings',
        name: 'settings',
        component: () => import('@/views/settings/')
      },
      {
        path: '/fans',
        name: 'fans',
        component: () => import('@/views/fans/')
      }

    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由导航守卫 ：所有的页面导航都会经过这里
router.beforeEach((to, from, next) => {
  // 如果要访问的页面不是/login,要检验登录状态
  // 如果没有登录，跳转到登录页面
  // 如果登录了，放行
  const { user } = store.state
  // 校验登录状态
  if (to.path !== '/login') {
    if (user) {
      next()
    } else {
      next('/login') // 跳转到登录页面
    }
  } else {
    // 登录了
    next()
  }
})

export default router
